import { Store } from "./../../model/Store";
import { Card } from "./../../model/Card";
import { Player } from "./../../model/Player";
import { ModelModule } from "/src/model/Module";
import SGS_Util from "../utils";
import { GameController } from "./game.controller";

export interface GameOptions {
	player: {
		count: number;
	};

	modules?: ModelModule[];
}
export class Game {
	private modules: ModelModule[] = [];
	private players: Player[] | undefined;
	private store: Store | undefined;

	//加载模块
	constructor(private gameOptions: GameOptions) {
		// 有模块则直接加载
		if (gameOptions.modules) {
			this.initModules(gameOptions.modules);
		}
	}

	// 手动加载
	initModules(modules: ModelModule[]) {
		if (this.modules.length > 0) {
			throw Error(
				"模块初始化后不允许被加载多次 @core/game/index.ts/Game/initModules"
			);
		}
		modules.forEach((v, k) => (this.modules[k] = v));
		this.initCard();
		this.initPlayer(this.gameOptions.player.count);
		this.initController();
	}

	private initCard() {
		if (this.store === undefined) {
			let INIT_CARD: Card[] = [];
			this.modules.forEach(module => {
				INIT_CARD.push(...module.provideCard());
			});
			this.store = new Store(SGS_Util.shuffle(INIT_CARD));
		} else {
			throw Error("Card类已经有定义 @core/game/index.ts/Game/initCard");
		}
	}

	private initPlayer(count: number) {
		if (this.players === undefined) {
			const INIT_PLAYER: Player[] = [];
			const SHUFFLE_CAMP = SGS_Util.shuffle(
				SGS_Util.provideSuitableCamps(count)
			);
			for (let i = 0; i < count; i++) {
				const newPlayer = new Player({
					index: i,
					camp: i === 0 ? "ZG" : SHUFFLE_CAMP[i - 1]
				});
				newPlayer.injectStore(this.store!);
				newPlayer.getCards(4);
				INIT_PLAYER.push(newPlayer);
			}
			this.players = INIT_PLAYER;
		} else {
			throw Error("Player类已经有定义 @core/game/index.ts/Game/initPlayer");
		}
	}

	private initController() {
		if (this.players && this.store) {
			new GameController(this.players, this.store, this.gameOptions);
		} else {
			throw Error(
				"Player和Store初始化失败，无法注入GameController类 @core/game/index.ts/Game/Controller"
			);
		}
	}
}
